package com.dyrj.ysk.controller;

import com.alibaba.fastjson.JSONObject;
import com.dyrj.ysk.constants.Constants;
import com.dyrj.ysk.util.CertUtil;
import com.dyrj.ysk.util.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * @author 吴侠志  2020/5/14
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/ysksdk")
public class CertController {

    /**
     * 读取公私钥串页面
     * @return
     */
    @RequestMapping(value = "/testKeyPairPage",method = RequestMethod.GET)
    public String testKeyPairPage(){
        return "ysksdk/testKeyPairPage";
    }

    /**
     * 校验公私钥证书
     * @return
     */
    @RequestMapping(value = "/testKeyPair",method = RequestMethod.POST)
    public String testKeyPair(@RequestPart("certFile") MultipartFile certFile,
                              @RequestPart("pfxFile") MultipartFile pfxFile,
                              @RequestParam("passwd") String passwd, Model model) throws Exception {
        File doc=new File(Constants.TMP_FILE_PATH);
        if(!doc.exists()){
            FileUtils.forceMkdir(doc);
        }
        File pfx=new File(Constants.TMP_FILE_PATH+ UUID.randomUUID()+".pfx");
        FileUtils.copyInputStreamToFile(pfxFile.getInputStream(),pfx);
        File cert=new File(Constants.TMP_FILE_PATH+ UUID.randomUUID()+".cer");
        FileUtils.copyInputStreamToFile(certFile.getInputStream(),cert);

        String pubKey= CertUtil.getPubKeyStr(cert.getAbsolutePath());
        String priKey=CertUtil.getPriKeyStr(pfx.getAbsolutePath(),passwd);

        String contenetStr="{\"TraderNo\":\"2000807949\",\"TranAmt\":\"1\",\"OrderName\":\"一个商品\",\"OrderRemark\":\"这是什么东西啊\",\"ClientType\":\"pc\",\"ClientNo\":\"10002\",\"CallBackNoticeUrl\":\"https://cloudpayweb-fat2.orangebank.com.cn/test/notifyUrl\",\"OrderSendTime\":\"20200514143317\",\"TraderOrderNo\":\"15894379969957wIzgU\",\"FrontSkipUrl\":\"https://cloudpayweb-fat2.orangebank.com.cn/test/jumpUrl\"}";
        JSONObject jsonObject = JSONObject.parseObject(contenetStr);
        String sign = RsaUtils.sign(jsonObject, priKey);
        boolean result=RsaUtils.check(JSONObject.parseObject(contenetStr) , sign, pubKey);
        model.addAttribute("privateKey",priKey);
        model.addAttribute("publicKey",pubKey);
        model.addAttribute("result",result);
        return "ysksdk/testKeyPairResult";
    }
}
